<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "jerry");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
// $wechatObj->responseMsg();

class wechatCallbackapiTest
{

	public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	exit;
        }
    }
       /**
        * 验证
        */
private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
    public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";             
				if($keyword=="julier")
                {
              		$msgType = "text";
                	$contentStr = "Please type some words . eg:your name or express number. your can try!^-^";
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;

                }elseif($keyword=="julie"||$keyword=="Julie"){
                    $msgType = "text";
                    $contentStr = "Yep . She is my GirlFriend.";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                
                }elseif($keyword=="CMD"||$keyword=="cmd"||$keyword=="酷梦者"||$keyword=="cooldreamer.com"){
                    $msgType = "text";
                    $contentStr = "酷梦者,网址cooldreamer.com；以下简称CMD。是几个身怀梦想的年轻人共同创建，只为追求提高和分享";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                   
                }elseif($keyword==""){
                    $msgType = "text";
                    $contentStr = "您可以尝试输入您的名字，可能会有意想不到的惊喜哦";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }else{
                    $msgType = "text";
                    $contentStr = "您可以尝试输入您的名字，可能会有意想不到的惊喜哦";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }

        }else {
        	echo "";
        	exit;
        }
    }
	



function get_utf8_string($content) {    
    //  将一些字符转化成utf8格式   
     $encoding = mb_detect_encoding($content, array('ASCII','UTF-8','GB2312','GBK','BIG5'));  
       return  mb_convert_encoding($content, 'utf-8', $encoding);
       }

//添加菜单
    public function menuadd($tpl_str)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$json->access_token;
        return $this->curlPostGet($url, 1, $tpl_str);
    }

    //删除菜单
    public function menudel()
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/menu/delete?access_token='.$json->access_token;
        return $this->curlPostGet($url, 2);
    }

    //获取用户发送消息
    public function GetMsg()
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr))
        {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $GMsg["fromUsername"] = $postObj->FromUserName;
            $GMsg["toUsername"] = $postObj->ToUserName;
            $GMsg["CreateTime"] = $postObj->CreateTime;
            $GMsg["MsgType"] = $postObj->MsgType;
            switch ($GMsg["MsgType"]) {
                case "text":
                    $GMsg["Content"] = $postObj->Content;
                    $GMsg["MsgId"] = $postObj->MsgId;
                    break;
                case "image":
                    $GMsg["PicUrl"] = $postObj->PicUrl;
                    $GMsg["MediaId"] = $postObj->MediaId;
                    $GMsg["MsgId"] = $postObj->MsgId;
                    break;
                case "voice":
                    $GMsg["MediaId"] = $postObj->MediaId;
                    $GMsg["Format"] = $postObj->Format;
                    $GMsg["MsgID"] = $postObj->MsgID;
                    //开启语音识别后
                    $GMsg["Recognition"] = $postObj->Recognition;
                    break;
                case "video":
                    $GMsg["MediaId"] = $postObj->MediaId;
                    $GMsg["ThumbMediaId"] = $postObj->ThumbMediaId;
                    $GMsg["MsgId"] = $postObj->MsgId;
                    break;
                case "location":
                    $GMsg["Location_X"] = $postObj->Location_X;
                    $GMsg["Location_Y"] = $postObj->Location_Y;
                    $GMsg["Scale"] = $postObj->Scale;
                    $GMsg["Label"] = $postObj->Label;
                    $GMsg["MsgId"] = $postObj->MsgId;
                    break;
                case "link":
                    $GMsg["Title"] = $postObj->Title;
                    $GMsg["Description"] = $postObj->Description;
                    $GMsg["Url"] = $postObj->Url;
                    $GMsg["MsgId"] = $postObj->MsgId;
                    break;
                case "event":
                    $GMsg["Event"] = $postObj->Event;
                    if ($GMsg["Event"] == "subscribe") //订阅
                    {
                        $GMsg["EventKey"] = $postObj->EventKey;
                        $GMsg["Ticket"] = $postObj->Ticket;
                    }
                    if ($GMsg["Event"] == "unsubscribe")//取消订阅
                    {}
                    if ($GMsg["Event"] == "SCAN")//已关注的情况下扫描二维码
                    {
                        $GMsg["EventKey"] = $postObj->EventKey;
                        $GMsg["Ticket"] = $postObj->Ticket;
                    }
                    if ($GMsg["Event"] == "LOCATION")//上报地理位置
                    {
                        $GMsg["Latitude"] = $postObj->Latitude;//维度
                        $GMsg["Longitude"] = $postObj->Longitude;//经度
                        $GMsg["Precision"] = $postObj->Precision;//地理位置精度
                    }
                    if ($GMsg["Event"] == "CLICK") //点击菜单
                    {
                        $GMsg["EventKey"] = $postObj->EventKey;//KEY值
                    }
                    if ($GMsg["Event"] == "VIEW")//点击菜单
                    {
                        $GMsg["EventKey"] = $postObj->EventKey;//跳转地址
                    }
                    break;
            }
            return $GMsg;
        }
        else
        {
            return "";
        }
    }

    //发送响应消息
    //发送文本消息时$msg_arr["msg"]为文本内容，发送多媒体消息时$msg_arr["mediaid"]为MediaId
    public function SendMsg($msgtype, $msg_arr = NULL)
    {
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        if (!empty($postStr))
        {
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $fromUsername = $postObj->FromUserName;
            $toUsername = $postObj->ToUserName;
            $time = time();

            if ($msgtype == "text")
            {
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            </xml>";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $msg_arr["msg"]);
            }
            if ($msgtype == "image")//图片消息
            {
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Image>
                            <MediaId><![CDATA[%s]]></MediaId>
                            </Image>
                            </xml>";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $msg_arr["mediaid"]);
            }
            if ($msgtype == "voice")//语音消息
            {
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Voice>
                            <MediaId><![CDATA[%s]]></MediaId>
                            </Voice>
                            </xml>";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $msg_arr["mediaid"]);
            }
            if ($msgtype == "video")//视频消息
            {
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Video>
                            <MediaId><![CDATA[%s]]></MediaId>
                            <Title><![CDATA[%s]]></Title>
                            <Description><![CDATA[%s]]></Description>
                            </Video> 
                            </xml>";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $msg_arr["mediaid"], $msg_arr['title'], $msg_arr['description']);
            }
            if ($msgtype == "music")//音乐消息
            {
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Music>
                            <Title><![CDATA[%s]]></Title>
                            <Description><![CDATA[%s]]></Description>
                            <MusicUrl><![CDATA[%s]]></MusicUrl>
                            <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
                            <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
                            </Music>
                            </xml>";
                $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $msg_arr["title"], $msg_arr['description'], $msg_arr['musicurl'], $msg_arr['hqmusicurl'], $msg_arr['mediaid']);
            }
            if ($msgtype == "news")//图文消息
            {
                $str_newslist = "";
                $arcc = count($msg_arr['news']);
                if ($arcc && $arcc < 11)//最大支持发送10条图文信息，否则返回错误
                {
                    $textTpl = "<xml>
                                <ToUserName><![CDATA[%s]]></ToUserName>
                                <FromUserName><![CDATA[%s]]></FromUserName>
                                <CreateTime>%s</CreateTime>
                                <MsgType><![CDATA[%s]]></MsgType>
                                <ArticleCount>%d</ArticleCount>
                                <Articles>%s</Articles>
                                </xml>";
                    $newlistTpl = "<item>
                                <Title><![CDATA[%s]]></Title> 
                                <Description><![CDATA[%s]]></Description>
                                <PicUrl><![CDATA[%s]]></PicUrl>
                                <Url><![CDATA[%s]]></Url>
                                </item>";
                    foreach ($msg_arr['news'] as $newslist)
                    {
                        $str_newslist .= sprintf($newlistTpl, $newslist['title'], $newslist['description'], $newslist['picurl'], $newslist['url']);
                    }
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgtype, $arcc, $str_newslist);
                }
                else
                {
                    $resultStr = "error";
                }
            }
            echo $resultStr;
        }
    }

    //发送客服消息
    public function SendCustomMsg($openid, $msgtype, $msg_arr = NULL)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token='.$json->access_token;
        if($msgtype == "text")//文本消息
        {
            $textTpl = '{
                            "touser":"%s",
                            "msgtype":"%s",
                            "%s":
                            {
                                 "content":"%s"
                            }
                        }';
            $data = sprintf($textTpl, $openid, $msgtype, $msgtype, $msg_arr["msg"]);
        }
        if($msgtype == "image")//图片消息
        {
            $textTpl = '{
                            "touser":"%s",
                            "msgtype":"%s",
                            "%s":
                            {
                              "media_id":"%s"
                            }
                        }';
            $data = sprintf($textTpl, $openid, $msgtype, $msgtype, $msg_arr["mediaid"]);
        }
        if($msgtype == "voice")//语音消息
        {
            $textTpl = '{
                            "touser":"%s",
                            "msgtype":"%s",
                            "%s":
                            {
                              "media_id":"%s"
                            }
                        }';
            $data = sprintf($textTpl, $openid, $msgtype, $msgtype, $msg_arr["mediaid"]);
        }
        if($msgtype == "video")//视频消息
        {
            $textTpl = '{
                            "touser":"%s",
                            "msgtype":"%s",
                            "%s":
                            {
                              "media_id":"%s",
                              "title":"%s",
                              "description":"%s"
                            }
                        }';
            $data = sprintf($textTpl, $openid, $msgtype, $msgtype, $msg_arr["mediaid"], $msg_arr["title"], $msg_arr["description"]);
        }
        if($msgtype == "music")//音乐消息
        {
            $textTpl = '{
                            "touser":"%s",
                            "msgtype":"%s",
                            "%s":
                            {
                              "title":"%s",
                              "description":"%s",
                              "musicurl":"%s",
                              "hqmusicurl":"%s",
                              "thumb_media_id":"%s" 
                            }
                        }';
            $data = sprintf($textTpl, $openid, $msgtype, $msgtype, $msg_arr["title"], $msg_arr["description"], $msg_arr["musicurl"], $msg_arr["hqmusicurl"], $msg_arr["mediaid"]);
        }
        if($msgtype == "news")//图文消息
        {
            $str_newslist = "";
            $arcc = count($msg_arr['news']);
            if ($arcc && $arcc < 11)//最大支持发送10条图文信息，否则返回错误
            {
                $textTpl = '{
                                "touser":"%s",
                                "msgtype":"%s",
                                "%s":{
                                    "articles": [%s]
                                }
                            }';
                $newlistTpl = '{
                                    "title":"%s",
                                    "description":"%s",
                                    "url":"%s",
                                    "picurl":"%s"
                                }';
                foreach ($msg_arr['news'] as $newslist)
                {
                    $str_newslist_arr[] = sprintf($newlistTpl, $newslist['title'], $newslist['description'], $newslist['url'], $newslist['picurl']);
                }
                $str_newslist = implode(",", $str_newslist_arr);

                $data = sprintf($textTpl, $openid, $msgtype, $msgtype, $str_newslist);
            }
            else
            {
                return "error";
            }
        }
        return $this->curlPostGet($url, 1, $data);

    }
    
    //获取用户基本信息
    public function GetUserInfo($openid)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/user/info?access_token='.$json->access_token.'&openid='.$openid.'&lang=zh_CN';
        return json_decode($this->curlPostGet($url, 2));
    }

    //创建分组
    public function CreateGroup($groupname)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/groups/create?access_token='.$json->access_token;
        $textTpl = '{"group":{"name":"%s"}}';
        $data = sprintf($textTpl, $groupname);
        return $this->curlPostGet($url, 1, $data);
    }

    //查询所有分组
    public function SearchGroup()
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/groups/get?access_token='.$json->access_token;
        return json_decode($this->curlPostGet($url, 2));
    }
    
    //查询用户所在分组
    public function SearchUserGroup($openid)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/groups/getid?access_token='.$json->access_token;
        $textTpl = '{"openid":"%s"}';
        $data = sprintf($textTpl, $openid);
        return $this->curlPostGet($url, 1, $data);
    }

    //修改分组名
    public function UpdateGroupName($groupid, $groupname)
    {
        $groupid = intval($groupid);
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/groups/update?access_token='.$json->access_token;
        $textTpl = '{"group":{"id":%d,"name":"%s"}}';
        $data = sprintf($textTpl, $groupid, $groupname);
        return $this->curlPostGet($url, 1, $data);
    }

    //移动用户分组
    public function MoveToGroup($openid, $groupid)
    {
        $groupid = intval($groupid);
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token='.$json->access_token;
        $textTpl = '{"openid":"%s","to_groupid":%d}';
        $data = sprintf($textTpl, $openid, $groupid);
        return $this->curlPostGet($url, 1, $data);
    }

    //获取关注者列表
    public function GetFollowList($nextopenid = NUll)
    {
        //关注者大于10000时递归取列表
        //global $followlist_arr;

        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='https://api.weixin.qq.com/cgi-bin/user/get?access_token='.$json->access_token."&next_openid=".$nextopenid;
        
        //关注者大于10000时递归取列表
        /*
        $followlist = json_decode($this->curlPostGet($url, 2),TRUE);
        if($followlist["next_openid"])
        {
            $followlist_arr[] = $followlist;
            $this->GetFollowList($followlist["next_openid"]);
        }
        return $followlist_arr;
        */

        return json_decode($this->curlPostGet($url, 2));
    }

    //网页授权获取用户基本信息
    //$redirect_url:用户指定跳转网址
    //$scope:0:snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid），1:snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地
    //$state:重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值
    public function GetCode($appid,$redirect_url,$scope,$state = NULL)
    {
        if (intval($scope) == 0)
        {
            $scope = 'snsapi_base';
        }
        else
        {
            $scope = 'snsapi_userinfo';
        }
        $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$redirect_url.'&response_type=code&scope='.$scope.'&state='.$state.'#wechat_redirect';
        return $url;
    }

    //拉取用户信息(需scope为 snsapi_userinfo)
    public function WebGetUserInfo($access_token,$openid,$lang = "zh_CN") //zh_CN 简体，zh_TW 繁体，en 英语
    {
        $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=".$lang;
        return json_decode($this->curlPostGet($url, 2));
    }

/*
图片（image）: 128K，支持JPG格式
语音（voice）：256K，播放长度不超过60s，支持AMR\MP3格式
视频（video）：1MB，支持MP4格式
缩略图（thumb）：64KB，支持JPG格式
注意，上传缩略图（thumb）返回的media_id名称为thumb_media_id，其他3中均为media_id
*/
    //上传多媒体文件
    public function UploadFile($fileurl, $type)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $realfile = dirname(__FILE__).$fileurl;
        $data = array("media"  => "@".$realfile);
        $url='http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token='.$json->access_token.'&type='.$type;
        return $this->curlPostGet($url, 1, $data);
    }
    
    //下载多媒体文件
    public function DownloadFile($media_id)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url='http://file.api.weixin.qq.com/cgi-bin/media/get?access_token='.$json->access_token.'&media_id='.$media_id;
        //return $this->curlPostGet($url, 2);
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $temp = curl_exec($ch);
        $http = curl_getinfo($ch);
        $http['media'] = $temp;
        return $http;
    }

    //生成带参数的二维码
    public function MakeQRcode($scene, $expire = 0)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url = 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$json->access_token;
        if($expire > 0)
        {
            $arr['expire_seconds'] = $expire;
            $arr['action_name'] = "QR_SCENE";
            $arr['action_info']["scene"]["scene_id"] = $scene;
            //$QRTpl = '{"expire_seconds": '.$expire.', "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": '.$scene.'}}}';
        }
        else
        {
            $arr['action_name'] = "QR_LIMIT_SCENE";
            $arr['action_info']["scene"]["scene_id"] = $scene;
            //$QRTpl = '{"action_name": "QR_LIMIT_SCENE", "action_info": {"scene": {"scene_id": '.$scene.'}}}';
        }
        $QRTpl = json_encode($arr);
        return $this->curlPostGet($url, 1, $QRTpl);
    }

    //通过ticket换取二维码
    public function GetQRcode($ticket)
    {
        $url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket='.urlencode($ticket);
        return $url;
    }
    
    //保存多媒体文件
    public function SaveMedia($media, $filename = NULL)
    {
        //视频文件不支持下载
        switch ($media["content_type"]) {
            case "image/jpeg":
                $suffix = ".jpg";
                break;
            case "audio/amr":
                $suffix = ".mp3";
                break;
        }

        if ($filename == NULL)
        {
            $filename = "sf_".time().$suffix;
        }

        $file = fopen($filename, 'w');
        if ($file !== false){
            $result = fwrite($file, $media["media"]);
            if($result)
            {
                fclose($file);
            }
            return $filename;
        }
        else
        {
            return false;
        }
    }
    
    //curl get post
    function curlPostGet($url, $type = 1, $data = NULL){
        if($type == 1)
        {
            $method = "POST";
        }
        else
        {
            $method = "GET";
        }
        $ch = curl_init();
        $header = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $temp = curl_exec($ch);
        /*
        if($type == 1)
        {
            if (curl_errno($ch)) {
                return false;
            }else{
                return true;
            }
        }
        */
        return $temp;
    }

    /*高级群发接口 注意：需要认证服务号才能使用该接口，否则群发返回 48001 api功能未授权*/
    //上传图文消息素材
    public function UploadImgTEXT($msg_arr)
    {
        $str_newslist = "";
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url = 'https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token='.$json->access_token;
        $textTpl = '{
                       "articles": [%s]
                    }';
        $newlistTpl = '{
                            "thumb_media_id":"%s",
                            "author":"%s",
                            "title":"%s",
                            "content_source_url":"%s",
                            "content":"%s",
                            "digest":"%s"
                        }';
        foreach ($msg_arr as $newslist)
        {
            $str_newslist_arr[] = sprintf($newlistTpl, $newslist['thumb_media_id'], $newslist['author'], $newslist['title'], $newslist['content_source_url'], $newslist['content'], $newslist['digest']);
        }
        $str_newslist = implode(",", $str_newslist_arr);
        $data = sprintf($textTpl, $str_newslist);

        return $this->curlPostGet($url, 1, $data);
    }

    //根据分组进行群发
    public function GroupSend($group_id, $media_id)
    {
        $access_token = $this->get_access_token(APPID, SECRET);
        $json=json_decode($this->curlPostGet($access_token,2));
        $url = 'https://api.weixin.qq.com/cgi-bin/message/mass/sendall?access_token='.$json->access_token;
        $textTpl = '{
                       "filter":{
                          "group_id":"%s"
                       },
                       "mpnews":{
                          "media_id":"%s"
                       },
                        "msgtype":"mpnews"
                    }';
        $data = sprintf($textTpl, $group_id, $media_id);
        return $this->curlPostGet($url, 1, $data);
    }

    /*end 高级群发接口*/

    //获取全局唯一票据
    public function get_access_token($appid, $secret, $grant_type = "client_credential")
    {
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type=".$grant_type."&appid=".$appid."&secret=".$secret;
        return $access_token;
    }

    //通过code换取网页授权access_token
    public function get_web_access_token($appid, $secret, $code, $grant_type = "authorization_code")
    {
        $access_token = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=".$grant_type;
        $json=json_decode($this->curlPostGet($access_token,2),TRUE);
        return $json;
    }

    //刷新access_token
    public function refresh_access_token($appid, $refresh_token, $grant_type = "refresh_token")
    {
        $url = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=".$appid."&grant_type=".$grant_type."&refresh_token=".$refresh_token;
        $json=json_decode($this->curlPostGet($access_token,2),TRUE);
        return $json;
    }
}

